package com.ai.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;


@Controller
@RequestMapping("/file")
public class UploadController {
	
    private static Logger logger = Logger.getLogger(UploadController.class);

	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String uploadFile(@RequestParam("file") CommonsMultipartFile file, String timestamp, HttpServletRequest request) throws Exception {
		String fileName = file.getOriginalFilename();
		if(timestamp == null || "".equals(timestamp)){
			timestamp = new Date().getTime() + "";
		}
		UserContext uc = (UserContext)request.getSession().getAttribute(Constants.USER_CONTEXT);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dirName = uc.getBgUser().getUsername() + File.separator + sdf.format(new Date());
		String relativePath = "uploadFiles" + File.separator + dirName;
		String fileSavePath = request.getSession().getServletContext().getRealPath("") + File.separator + relativePath;
		logger.info("------------fileSavePath---------:"+ fileSavePath);
		File newFile = new File(fileSavePath);
		newFile.mkdirs();
		String finalFileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
		newFile = new File(fileSavePath + File.separator + finalFileName);
		try {
			file.transferTo(newFile);
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return relativePath + File.separator + finalFileName;
	}
}

